package taskTracker;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

public class ReportsManager {
	
	public class TimeSummary {
		public long duration;
	}
	
	public class ProjectTimeSummary extends TimeSummary {
		public Project project;
	}
	
	public class TaskTimeSummary extends TimeSummary {
		public Task task;		
	}
	
	public static final ReportsManager instance = new ReportsManager();
	
	private ReportsManager() {
	}
	
	/**
	 * Get summary of time spent on each project
	 * @return vector of ProjectTimeSummary or TaskTimeSummary, depending on
	 * whether a project was passed or not, such that:
	 * if a project is passed then will return time per task within that project, 
	 * o.w. will return time per task
	 */
	public Enumeration getTimeSummary(long from, long to, Project project, Vector tags){
		Vector timeEntries;
		// if there were tags passed then, get entries tagged with these tags
		// else, get all entries
		if(tags != null && tags.size() > 0){
			timeEntries = TimeEntries.getInstance().getTimeEntriesforTags(tags);
		} else {			
			timeEntries = TimeEntries.getInstance().getTimeEntries(); 
		}
		
		Hashtable resultHash = new Hashtable();		
		
		for(int i = 0; i < timeEntries.size(); i++){
			TimeEntry entry = (TimeEntry)timeEntries.elementAt(i);				

			// get time per task
			if(project != null){
				if(entry.getTask().getParent() != project)
					continue;

				long duration = entry.getIntersectedTimeSpan(from, to);
				if (duration > 0) {

					TaskTimeSummary summary = (TaskTimeSummary)resultHash.get(entry.getTask());

					if(summary == null){
						summary = new TaskTimeSummary();
						resultHash.put(entry.getTask(), summary);
					}			

					summary.task = entry.getTask();
					summary.duration += duration;
				}
			} else {
				Project taskProject = entry.getTask().getParent();

				long duration = entry.getIntersectedTimeSpan(from, to);
				if (duration > 0) {
					ProjectTimeSummary summary;
					
					if(taskProject  == null)
						continue;
					
					summary = (ProjectTimeSummary)resultHash.get(taskProject );
					
					if(summary == null){		
						summary = new ProjectTimeSummary();
						resultHash.put(taskProject, summary);
					}
					
					summary.project = taskProject ;
					summary.duration += duration;
				}
			}
			
						
		}		
		
		return resultHash.elements();
	}	
}
